/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package azhar.com;

import java.util.ArrayList;
import javax.swing.JTable;
import javax.swing.table.DefaultTableModel;

/**
 *
 * @author Al-Insan
 */
public class TableOperation {

    private DefaultTableModel dataModel;

    public void insertData(JTable table, String[] data) {
        dataModel = (DefaultTableModel) table.getModel();
        table.setModel(dataModel);
        dataModel.insertRow(0, data);
    }

    public void insertAtLast(JTable table, String[] data) {
        dataModel = (DefaultTableModel) table.getModel();
        table.setModel(dataModel);
        dataModel.addRow(data);
    }

    public void updateData(JTable table, String [] data, int index) {
        for (int i = 0; i < table.getColumnCount(); i++) {
            table.setValueAt(data[i], index, i);
        }
    }

    public void deleteData(JTable table, int[] index) {
        dataModel = (DefaultTableModel) table.getModel();
        table.setModel(dataModel);
        for (int i = index.length-1; i >=0 ; i--) {
            dataModel.removeRow(index[i]);
        }
    }

    public String[] getValues(JTable table, String colName) {
        String[] numbers = new String[table.getSelectedRows().length];
        for (int i = 0; i < numbers.length; i++) {
            numbers[i] = (String) table.getValueAt(table.getSelectedRows()[i], getColumnIndex(table, colName));
        }
        return numbers;
    }

    public int getColumnIndex(JTable table, String name) {
        int index = 0;
        for (int i = 0; i < table.getColumnCount(); i++) {
            index = i;
            if (table.getColumnName(i).equals(name)) {
                break;
            }
        }
        return index;
    }
}
